---
import type { CollectionEntry } from 'astro:content';
import PillListFlat from '@components/Lists/PillListFlat';
import OwnersList from '@components/Lists/OwnersList';
import VersionList from '@components/Lists/VersionList.astro';
import { buildUrl } from '@utils/url-builder';
import { ScrollText } from 'lucide-react';
import { getOwner } from '@utils/collections/owners';
import { isChangelogEnabled } from '@utils/feature';

interface Props {
  entity: CollectionEntry<'entities'>;
}

const { entity } = Astro.props;

const ownersRaw = entity.data?.owners || [];
const owners = await Promise.all<ReturnType<typeof getOwner>>(ownersRaw.map(getOwner));
const filteredOwners = owners.filter((o) => o !== undefined);

// @ts-ignore
const services = (entity.data.services as CollectionEntry<'services'>[]) || [];
// @ts-ignore
const domains = (entity.data.domains as CollectionEntry<'domains'>[]) || [];

const attachments = entity.data.attachments || [];

const attachmentsList = attachments.map((a) => {
  const attachmentIsURL = typeof a === 'string';
  return {
    label: attachmentIsURL ? a : (a.title ?? a.url),
    href: attachmentIsURL ? a : a.url,
    icon: attachmentIsURL ? 'ExternalLinkIcon' : (a.icon ?? 'ExternalLinkIcon'),
    target: '_blank' as const,
    subgroup: attachmentIsURL ? undefined : (a.type ?? ''),
  };
});

const ownersList = filteredOwners.map((o) => ({
  label: o.data.name,
  type: o.collection,
  badge: o.collection === 'users' ? o.data.role : 'Team',
  avatarUrl: o.collection === 'users' ? o.data.avatarUrl : '',
  href: buildUrl(`/docs/${o.collection}/${o.data.id}`),
}));

const servicesList = services.map((p) => ({
  label: p.data.name,
  badge: p.collection,
  color: 'pink',
  collection: p.collection,
  tag: `v${p.data.version}`,
  href: buildUrl(`/docs/${p.collection}/${p.data.id}/${p.data.version}`),
}));

const domainsList = domains.map((p) => ({
  label: p.data.name,
  badge: p.collection,
  color: 'blue',
  collection: p.collection,
  tag: `v${p.data.version}`,
  href: buildUrl(`/docs/${p.collection}/${p.data.id}/${p.data.version}`),
}));

const shouldRenderSideBarSection = (section: string) => {
  if (!entity.data.detailsPanel) {
    return true;
  }
  // @ts-ignore
  return entity.data.detailsPanel[section]?.visible ?? true;
};
---

<aside class="sticky top-28 left-0 space-y-8 h-full overflow-y-auto py-4">
  <div class="">
    {
      shouldRenderSideBarSection('domains') && (
        <PillListFlat
          title={`Domains (${domainsList.length})`}
          pills={domainsList}
          emptyMessage={`This entity is not used in any domains.`}
          color="blue"
          client:load
        />
      )
    }
    {
      servicesList.length > 0 && shouldRenderSideBarSection('services') && (
        <PillListFlat
          title={`Services (${servicesList.length})`}
          pills={servicesList}
          emptyMessage={`This entity is not used in any services.`}
          color="pink"
          client:load
        />
      )
    }
    {
      entity.data.versions && shouldRenderSideBarSection('versions') && (
        <VersionList versions={entity.data.versions} collectionItem={entity} />
      )
    }
    {
      entity.data.attachments && shouldRenderSideBarSection('attachments') && (
        <PillListFlat
          title={`Attachments (${attachmentsList.length})`}
          pills={attachmentsList}
          emptyMessage={`This entity does not have any attachments.`}
          color="pink"
          client:load
        />
      )
    }
    {
      filteredOwners.length > 0 && shouldRenderSideBarSection('owners') && (
        <OwnersList
          title={`Owners (${filteredOwners.length})`}
          owners={ownersList}
          emptyMessage={`This entity does not have any documented owners.`}
          client:load
        />
      )
    }

    {
      isChangelogEnabled() && shouldRenderSideBarSection('changelog') && (
        <div class="space-y-2">
          <a
            href={buildUrl(`/docs/${entity.collection}/${entity.data.id}/${entity.data.latestVersion}/changelog`)}
            class="flex items-center space-x-2 justify-center text-center rounded-md w-full bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-100/60 hover:text-primary"
          >
            <ScrollText strokeWidth={2} size={16} />
            <span class="block">Read changelog</span>
          </a>
        </div>
      )
    }
  </div>
</aside>
